package com.demo.api.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: cja
 * @date: 2019/11/13 20:02
 */
@Slf4j
@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResultT exceptionHandler(Exception e) {
        log.error("发生错误:", e);
        //客户端请求错误
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ve = (MethodArgumentNotValidException) e;
            StringBuilder error = new StringBuilder();
            if (ve.getBindingResult().getErrorCount() > 0) {
                for (ObjectError oe : ve.getBindingResult().getAllErrors()) {
                    error.append(oe.getDefaultMessage()).append(";");
                }
            }
            return ResultT.error(ResultT.CLIENT_ERROR_CODE, StringUtils.isEmpty(error) ? "数据不符合校验" : error.toString());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResultT.error(ResultT.CLIENT_ERROR_CODE, "请求方式错误");
        } else if (e instanceof BussException) {
            BussException be = (BussException) e;
            return ResultT.error(be.getCode(), be.getMsg());
        }
        return ResultT.error(ResultT.SERVER_ERROR_CODE, "未知错误");
    }
}
